import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入路由信息
import routes from './routes'
// 引入store
import store from '@/store'

// 使用插件
Vue.use(VueRouter)

// 先保存push,replace
let OriginPush = VueRouter.prototype.push;

//重写push
// location参数接收跳转路径
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        OriginPush.call(this, location, resolve, reject)
    } else {
        OriginPush.call(this, location, () => { }, () => { })
    }
}

let router = new VueRouter({
    routes,
    // 路由滚动行为
    scrollBehavior(to, from, savedPosition) {
        return { y: 0 }
    }
})

// 全局守卫
router.beforeEach(async (to, from, next) => {
    next()
    let token = store.state.user.token
    let name = store.state.user.userInfo.name
    // 已经登录
    if (token) {
        if (to.path == '/login' || to.path == '/register') {
            next('/')
        } else {
            // 已经登录且访问的不是登录和注册组件
            // 拥有用户信息
            if (name) {
                next()
            } else {
                try {
                    await store.dispatch('userInfo')
                    next()
                } catch (error) {
                    // token失效
                    store.dispatch('userLogout')
                    next('/login')
                }
            }
        }
    }else{
        // 用户未登录时
        let toPath = to.path
        if(toPath.indexOf('trade')!==-1 || toPath.indexOf('pay')!==-1 || toPath.indexOf('center')!==-1){
            // 将未登录时想去的路由设置为query参数存储在地址中,修改登录组件的路由去向
            next('/login?redirect='+toPath)
        }else{
            next()
        }
    }
})

export default router